import PageLayout from "@/components/PageLayout";
import {
  Button,
  Center,
  Flex,
  Group,
  Pagination,
  Paper,
  Table,
  Text,
} from "@mantine/core";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import UserPill from "@/components/UserPill";
import When from "@/components/When";
import { DateTimePicker } from "@mantine/dates";
import { useForm } from "@mantine/form";
import { IconSearch } from "@tabler/icons-react";
import dayjs from "dayjs";
import { useParams } from "react-router-dom";
import { useImmer } from "use-immer";
import ProductPill from "../../components/ProductPill";

export default function StockOperationLogList() {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const { id } = useParams();

  const [pagingCondition, setPagingCondition] = useImmer({
    pageIndex: 0,
    pageSize: 10,
    start: dayjs().subtract(7, "days").toDate(),
    end: new Date(),
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      start: dayjs().subtract(7, "days").toDate(),
      end: new Date(),
    },
    validate: {},
  });

  const search = (values) => {
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const logQuery = tanstackQuery("/api/admin/products/stock/logs", {
    ...pagingCondition,
    start: dayjs(pagingCondition.start).format("YYYY-MM-DDTHH:mm:ss"),
    end: dayjs(pagingCondition.end).format("YYYY-MM-DDTHH:mm:ss"),
    pageNo: pagingCondition.pageIndex,
    productId: id || "",
    pageSize: pagingCondition.pageSize,
  });

  const totalPages = logQuery.data?.totalPages;
  const rows = logQuery.data?.content.map((log, index) => (
    <Table.Tr key={index}>
      <Table.Td>
        <Text>{index + 1}</Text>
      </Table.Td>
      <Table.Td>
        <Text>{dayjs(log.createdAt).format("YYYY/MM/DD HH:mm:ss")}</Text>
      </Table.Td>
      <When condition={!id}>
        <Table.Td>
          <ProductPill productId={log.subjectId} />
        </Table.Td>
      </When>

      <Table.Td>
        <Text>{log.details.delta}</Text>
      </Table.Td>
      <Table.Td>
        <UserPill userId={log.operatorId} />
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout
      title={
        id ? (
          <Group>
            库存变动记录 -
            <ProductPill productId={id} />
          </Group>
        ) : (
          "库存变动记录"
        )
      }
    >
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="flex-end"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          <DateTimePicker
            description="时间开始"
            {...searchForm.getInputProps("start")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <DateTimePicker
            description="时间结束"
            {...searchForm.getInputProps("end")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <Button type="submit" rightSection={<IconSearch size={14} />}>
            搜索
          </Button>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Paper p="md">
          <Table verticalSpacing={"sm"}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th w={"4%"}></Table.Th>
                <Table.Th w={"20%"}>时间</Table.Th>
                <When condition={!id}>
                  <Table.Th w={"36%"}>商品</Table.Th>
                </When>
                <Table.Th w={"20%"}>变动值</Table.Th>
                <Table.Th w={"20%"}>操作人</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>{rows}</Table.Tbody>
          </Table>
        </Paper>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}
